<template>

	<view style="background-color: #f9f9f9;">

		<!-- 登录 -->
		<view class="content" v-show="showLogin">
			<view class="content-log">
				<view class="logt1"><text class="log-t1">PengLin鹏邻</text></view>
				<view class="logt2"><text class="logt-t2">金鹏物业二手房</text></view>
			</view>

			<view class="content-title">
				<view class="title-t"><text>登录后才能委托卖房/出租、买房/租房,查看自己委托的内容</text></view>
			</view>

			<view class="content-but">
				<!-- <button plain="true" class="butt" open-type="getUserInfo" @getuserinfo="getUserInfo"><text>微信授权登录</text></button> -->

				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">获取手机号码</button>

			</view>

			<u-modal v-model="show" title="授权手机号" confirm-text="授权" @confirm="confirm">
				<u-form style="width: 100%;" :model="model" :rules="rules" ref="uForm" :error-type="errorType">
					<!-- 手机号 -->
					<view class="pub-view">
						<view class="pub-text">
							<text>手机号</text>
						</view>
						<view class="pub-content col">
							<u-form-item prop="initPhone">
								<u-input v-model="model.initPhone" placeholder="输入手机号" />
							</u-form-item>
						</view>
					</view>
				</u-form>
			</u-modal>

			<!-- 及时反馈组件 -->
			<HMmessages ref="HMmessages" @complete="HMmessages = $refs.HMmessages" @clickMessage="clickMessage"></HMmessages>
		</view>

	</view>
</template>

<script>
	// 解构console
	var { log } = console;

	import { openidSelectUrl } from '../../api/request.js';
	import { openidSubmitUrl } from '../../api/request.js';
	import { publicing } from '../../api/api.js';
	import { phone } from '../../api/request.js';
	import { errdata } from '../../api/errdata.js';

	// 引入即可反馈组件
	import HMmessages from '../../components/HM-messages/HM-messages.vue';

	// 引入公用存储用户登录
	import { login } from '../../api/list.js';
	var db = wx.cloud.database();
	var users = db.collection('user');
	
	var WXBizDataCrypt = require('../../utils/cryptojs-master/WXBizDataCrypt')
	var AppId = 'wx5f26e5edb29058a6'
	var AppSecret = 'ea0bd6cf6203a5431175f0e4ca293696'
	var sessionKey ='';
	
	export default {
		components: { HMmessages },

		data() {
			return {
				// 授权弹出框
				show: false,
				// 授权页面
				showLogin: false,
				// 微信标识
				openid: '',

				// 根据访问人手机号，获取访问记录 调用地址
				openidSelectUrl: '',
				// 根据访问人手机号，获取访问记录 入参
				param: '',
				// 手机号
				phone: '',

				// 表单内的数据
				model: {
					initPhone: ''
				},

				submitData: '',
				// 解密code
				code:'',
				// session_key
				sessionKey:'',
				
				

				// 表单校验规则
				rules: {
					// 访问人号码
					initPhone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'], // change：字段值发生变化时校验 blur：输入框失去焦点时触发
						},
						{
							validator: (rule, value, callback) => {
								if (!(/^1[3456789]\d{9}$/.test(value))) {
									return false;
								} else {
									return true;
								}
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],

					// 错误提示类型
					errorType: ['toast'],
				}
			}
		},

		onLoad(e) {
			var that = this
			wx.login({
				success: function(res) {
					console.log("res.code:"+res.code)
					// that.setData({
					// 	code: res.code,
					// })
					// this.code = res.code,
					
					wx.request({
						url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx5f26e5edb29058a6&secret=ea0bd6cf6203a5431175f0e4ca293696&js_code=' +
							res.code + '&grant_type=authorization_code',
						method: 'POST',
						header: {
							'content-type': 'application/json'
						},
						success: function(res) {
							console.log("res.data.session_key:"+res.data.session_key)
							console.log("res.data.openid:"+res.data.openid)
							sessionKey = res.data.session_key
						}
					})
				}
			})
		},

		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},

		methods: {
			getPhoneNumber(e) {
				var that = this
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					var pc = new WXBizDataCrypt(AppId, sessionKey)
					var data = pc.decryptData(e.detail.encryptedData , e.detail.iv)
					console.log('解密后 data: ', data.phoneNumber)
					
					// 保存用户手机号到vuex仓库中
					this.$store.commit('phonemuta', data.phoneNumber)
					
				} else {
					console.log('用户点击了拒绝');
				}
			},

			// 请求数据库看看用户有没有登录
			ifUser() {
				users.get()
					.then((res) => {
						console.log(res)
						if (res.data.length === 0) {
							// 没有登陆过
							this.showLogin = true


						} else {
							this.openid = res.data[0]._openid
							log('登录获取的openid值为:' + this.openid)
							this.$store.commit('openidmuta', this.openid)
							wx.reLaunch({
								url: 'visitorIndex'
							});
						}
					})
					.catch((err) => {
						console.log(err)
					})
			},

			// 按钮：电话咨询
			call() {
				log(phone)
				uni.makePhoneCall({
					phoneNumber: phone
				});
			},

			// 确认按钮，提交openid以及手机号
			confirm() {
				this.$refs.uForm.validate(valid => {
					log(valid)
					if (valid) {
						log("进行授权")
						this.submitData = {
							phone: this.model.initPhone,
							openId: this.openid
						}
						log("传入值为：" + JSON.stringify(this.submitData))

						this.openidSubmitUrl = openidSubmitUrl
						publicing(this.openidSubmitUrl, this.submitData)
							.then(res => {
								log("提交openid返回结果:" + res)
								if (res.statusCode == 200) {
									// 登陆成功
									this.$nextTick(() => {
										log("登录成功")

										this.$store.commit('openidmuta', this.openid)
										//dom更新循环结束之后的延迟回调
										this.HMmessages.show('授权成功', {
											icon: 'success',
											iconColor: '#ffffff',
											fontColor: '#ffffff',
											background: 'rgba(240, 142, 35, 0.8)'
										});

										setTimeout(() => {
											wx.reLaunch({
												url: 'visitorIndex'
											});
										}, 1500);
									});
								}
							})
					} else {
						let errs = '手机号有误!'
						errdata.errlist(errs)
						return false
					}
				})
			},

			// 发起登录取到用户信息
			// getUserInfo(event) {
			// 	console.log(event);
			// 	// Step1 存储用户信息到user数据库
			// 	let user = event.detail.userInfo;
			// 	login(user)
			// 		.then(res => {
			// 			console.log("res的数据为:" + JSON.stringify(res));

			// 			// Step2 获取用户openid
			// 			users.get()
			// 				.then((res) => {
			// 					this.openid = res.data[0]._openid
			// 				})
			// 			this.show = true
			// 		})
			// 		.catch(err => {
			// 			console.log(err);
			// 		});
			// }


		},

		// 判断用户是否登录
		onShow() {
			// 请求数据库看看用户有没有登录
			this.ifUser()
		}
	}
</script>

<style scoped>
	page {
		background-color: #F5F5F5;
	}

	.content {
		display: flex;
		flex-direction: column;
	}

	.content-log {
		height: 400upx;
	}

	.logt1 {
		margin-top: 90upx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.logt2 {
		margin-top: 10upx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.log-t1 {
		font-size: 70upx;
		font-weight: bold;
		color: #f08e23;
		letter-spacing: 8upx;
	}

	.logt-t2 {
		font-size: 35rpx;
		font-weight: bold;
		color: #8e8e8e;
		letter-spacing: 30upx;
	}

	.content-title {
		width: 100%;
	}

	.title-t {
		margin: 0 auto;
		width: 70%;
		/* background-color: #9befff; */
		text-align: center;
	}

	.title-t text {
		font-size: 30upx;
		color: #8e8e8e;
		letter-spacing: 3upx;
	}

	.content-but {
		margin-top: 50upx;
		width: 100%;
	}

	.butt {
		width: 90%;
		margin: 0 auto;
		background-color: #f08e23;
		border: none;
		border-radius: 40upx;
	}

	.butt text {
		font-size: 34upx;
		letter-spacing: 10upx;
		color: #ffffff;
	}

	/* 发布委托列表 */
	.publish-v {
		margin: 40upx 30upx 0 30upx;
		width: 90%;
	}

	.publish-frame {
		border-radius: 20upx;
		padding-top: 12upx;
		height: 327upx;
		width: 100%;
		display: flex;
		/* justify-content: space-between; */
		justify-content: space-around;
		flex-wrap: wrap;
		background-color: #FFFFFF;
	}

	.publish-cata {
		width: 48%;
		height: 150upx;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-around;
		border-radius: 15upx;
	}

	.publish-content {
		display: flex;
		flex-direction: column;
	}

	.publish-content text:nth-child(1) {
		padding-bottom: 7upx;
		font-size: 30upx;
		font-weight: bold;
		letter-spacing: 3upx;
	}

	.publish-content text:nth-child(2) {
		font-size: 25upx;
		color: #666666;
	}

	.publish-image {
		width: 90upx;
		height: 90upx;
	}

	.txt {
		margin-top: 40upx;
		font-size: 35upx;
		font-weight: bold;
		letter-spacing: 3upx;
	}

	.none {
		height: 100upx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.none text {
		text-align: center;
		font-size: 25upx;
		color: #cccccc;
		margin: 0 auto;
	}

	.container {
		background-color: #F9F9F9;
		width: 103%;
		/* height: 1000upx; */
		border-radius: 20upx;
		margin-top: 10upx;
	}


	.entrustView {
		margin-top: 20upx;
		height: 190upx;
		/* background-color: #fafafa; */
		border-radius: 30upx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		/* border-bottom: 1px solid #e6e6e6; */

	}

	.en_title text {
		padding-bottom: 7upx;
		font-size: 30upx;
		font-weight: bold;
		letter-spacing: 3upx;
	}

	.en_title {
		margin-left: 30upx;
		padding-right: 20upx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		/* flex-grow:2; */
	}

	.publish-image {
		width: 110upx;
		height: 110upx;
	}

	.tit {
		margin: 16upx 0 16upx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		font-size: 25upx;
		/* flex-grow:3; */
		/* width: 50%; */

		/* 	white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis; */

	}

	.titl {
		margin: 16upx 0 16upx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		font-size: 25upx;
		margin-right: 30upx;
		/* flex-grow:2; */
	}

	.pl {
		width: 160upx;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tit text {
		font-size: 28upx;
		letter-spacing: 2upx;
		color: #666666;
	}

	.titl text {
		font-size: 28upx;
		letter-spacing: 2upx;
		color: #666666;
	}

	.shadow {
		box-shadow: #F7F7F7 0px 0px 20px;
	}

	.pub-view {
		height: 110upx;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px #e6e6e6 solid;
		margin-left: 60upx;
	}

	.pub-content {
		width: 74%;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
</style>
